package cn.dvptech.remotemate.screenmirror.decode;

import android.media.MediaCodec;
import android.os.SystemClock;
import android.util.Log;

import java.nio.ByteBuffer;

import cn.dvptech.remotemate.screenmirror.screenHelper.Frame;
import cn.dvptech.remotemate.screenmirror.server.NormalPlayQueue;
import timber.log.Timber;

/**
 *    author  : ulongx
 *    website : www.dvptech.cn
 *    date    : 2024/7/21
 *    desc    : 解码线程, 解码判断类型, 分开解析
 */
public class DecodeThread extends Thread {
    private static final String TAG = "DecodeThread";
    private final NormalPlayQueue playQueue;
    private volatile boolean isRunning = true;
    private final VideoPlay videoPlay;
    private final AudioPlay audioPlay;

    public DecodeThread(MediaCodec mediaCodec, NormalPlayQueue playQueue) {
        this.playQueue = playQueue;
        videoPlay = new VideoPlay(mediaCodec);
        audioPlay = new AudioPlay();
    }

    @Override
    public void run() {
        while (isRunning) {
            Frame frame = playQueue.takeByte();
            if (frame == null) {
                SystemClock.sleep(1);
                continue;
            }
            switch (frame.getType()) {
                case Frame.KEY_FRAME:
                case Frame.NORMAL_FRAME:
                    try {
                        videoPlay.decodeH264(frame.getBytes());
                    } catch (Exception e) {
                        Timber.e( "%s frame Exception %s", TAG , e.toString());
                    }
                    break;
                case Frame.SPSPPS:
                    try {
                        ByteBuffer bb = ByteBuffer.allocate(frame.getPps().length + frame.getSps().length);
                        bb.put(frame.getSps());
                        bb.put(frame.getPps());
                        videoPlay.decodeH264(bb.array());
                    } catch (Exception e) {
                        Timber.e( "%s sps pps Exception %s", TAG , e.toString());
                    }
                    break;
                case Frame.AUDIO_FRAME:
                    try {
                        audioPlay.playAudio(frame.getBytes(), 0, frame.getBytes().length);
                    } catch (Exception e) {
                        Timber.e("audio Exception %s", e.toString());
                    }
                    break;
            }
        }
    }

    /**
     * 停止解码过程并释放资源。
     */
    public void shutdown() {
        isRunning = false;
        this.interrupt();
        videoPlay.release();
        audioPlay.release();
    }
}
